<template>

  <div>

    <Card>

      <div class="p-relative" style="padding-top: 10px;">
        <div @click="refresh" class="p-absolute refresh-btn">
          <Icon size='24' type="md-refresh" />
        </div>
        <div class="flex-box search-area">
          <div class="flex-item search-btn">
            <Button type="warning" @click='create'>添加</Button>
          </div>

        </div>
      </div>
      <Table :columns="tableOption" :data="data.list" border :no-data-text="loadingText ? loadingText : '暂无数据'" border
        ref="tables" editable search-place="top">

        <template slot-scope="{ row, index }" slot="type">
          {{row.type==1?row.name:''}}
        </template>
        <template slot-scope="{ row, index }" slot="action">
          <div class="flex-box flex-center flex-margin">
            <Button type='warning' @click="edit(row, index)" size='small'>编辑</Button>
            <Button type='error' @click="del(row, index)" size='small' v-if="row.id!=1">删除</Button>
          </div>
        </template>
      </Table>
      <Page class="foot-page" :current='page.current' :total="page.total" :page-size="page.pageSize" show-total
        show-elevator @on-change="changepage"></Page>

    </Card>


    <!-- 添加弹窗 -->
    <Modal v-model="createModal" :title="createTitle" width='700'>
      <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="80">
        <!-- 当前登录账号是总后台账号才显示 -->
        <FormItem label="账号类型" prop="type" v-if="data.account_type==0">
          <Select v-model="formValidate.type" style="width:130px" placeholder='请选择账号类型' @on-change="changType">
            <Option value="0">总后台</Option>
            <Option value="1">门店</Option>
          </Select>
        </FormItem>

        <FormItem label="名称" prop="nickname">
          <Input v-model="formValidate.nickname" placeholder="请输入名称"></Input>
        </FormItem>
        <FormItem label="电话" prop="mobile">
          <Input v-model="formValidate.mobile" placeholder="请输入手机号,手机号即为登录账号"></Input>
        </FormItem>
        <FormItem label="账号角色">
          <Select v-model="formValidate.group_id" placeholder='请选择账号角色赋予账号相应操作权限'>
            <Option :value="item.id" v-for="item in data.roleList">{{item.name}}</Option>

          </Select>
        </FormItem>
        <FormItem label="登录密码" prop="password" v-if="isAdd">
          <Input v-model="formValidate.password" type="password" placeholder="请输入登录密码"></Input>
        </FormItem>
        <FormItem label="确认密码" prop="cpassword" v-if="isAdd">
          <Input v-model="formValidate.cpassword" type="password" placeholder="请输入确认密码"></Input>
        </FormItem>
        <!-- 当前登录账号是门店超级管理账号才显示 -->
        <FormItem label="归属门店" v-if="formValidate.type==1">
          <Select v-model="formValidate.store_id" filterable  placeholder='请选择归属门店'>
             <Option :value="item.id" v-for="item in data.storeList">{{item.name}}</Option>
          </Select>
        </FormItem>
        <FormItem label="状态">
          <RadioGroup v-model="formValidate.status">
            <Radio label="1">启用</Radio>&nbsp;&nbsp;&nbsp;&nbsp;
            <Radio label="0">禁用</Radio>&nbsp;&nbsp;&nbsp;&nbsp;
          </RadioGroup>
        </FormItem>

      </Form>
      <div slot="footer">
        <Button @click='createModal=false'>取消</Button>
        <Button type="warning" @click="save('formValidate')" :disabled="isDisable" :loading="isLoading">保存</Button>
      </div>
    </Modal>


    <!-- 删除弹窗 -->
    <Modal v-model="delModal" title="提示" width="250">
      <p class="font16">
        <Icon class='del-tips-icon' type="ios-alert-outline" color='orange' size='22' />确定删除该数据吗？
      </p>
      <div slot="footer">
        <Button @click='delModal=false'>取消</Button>
        <Button type="primary" @click='confirmDel'>确定</Button>
      </div>
    </Modal>



  </div>
</template>
<!-- 公共弹框，成功，失败，报错，loading -->
<script>
  import {
    mapState
  } from 'vuex'
  import {
    permission
  } from '@/config/permission.js'

  // 接口
  import {
    getList,
    add,
    put,
    del

  } from '@/api/setting-group/manager'
  import {
    tableOption
  } from '../../../data/setting-group/manager.js'
  import Tables from '_c/tables'

  import {
    getTableData
  } from '@/api/data'

  export default {
    name: 'tables_page',
    components: {
      Tables

    },
    created() {
      let _this = this
     this.$nextTick(function() {
       // 权限校验
       // _this.role_list = permission(this.roles, 'manager/getList')
       _this.role_add = permission(this.roles, 'manager/add')
       _this.role_edit = permission(this.roles, 'manager/edit')
       _this.role_del = permission(this.roles, 'manager/delete')

     })

      this.getList()
    },
    watch: {

    },
    mounted() {

    },
    computed: {
      ...mapState({
        roles: state => state.user.roles
      })

    },
    data() {
      let _this = this;
      var validatePwd = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入密码'));
        } else {
          if (_this.formValidate.password !== '') {
            _this.$refs.formValidate.validateField('cpassword'); //formValidate,ref
          }
          callback();
        }
      };
      var validateRepwd = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== _this.formValidate.password) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      };

      return {
        // 权限标识
        role_add: false,
        role_edit: false,
        role_del: false,
        delModal: false,
        createModal: false,
        createTitle: '添加',
        isAdd: true, // 新增true,修改false
        detailModal: false,
        loadingText: '',
        tableOption: tableOption,
        page: {
          current: 1,
          total: 0,
          pageSize: 10,

        },
        data: {
          storeList:[],
          roleList: [],
          detail: [],
          list: [],
          account_type: '', //登录账号类型  0总后台 1门店
          account_pid: '' //0表示超级管理账号
        },
        formValidate: {
          username: '',
          status: '1',
          nickname: '',
          password: '',
          cpassword: '',
          mobile: '',
          type: '0',
          group_id: 0,
          store_id:0

        },
        isDisable: false, // 新增时提交按钮点击状态
        isLoading: false, // 新增时提交按钮loading状态

        ruleValidate: {
          group_id: [{
            required: true,
            message: '请选择账号角色',
            trigger: 'blur'
          }],
          nickname: [{
            required: true,
            message: '请输入姓名',
            trigger: 'blur'
          }],
          password: [{
            required: true,
            message: '请输入登录密码',
            trigger: 'blur'
          }, {
            validator: validatePwd,
            trigger: 'blur'
          }],
          cpassword: [{
            required: true,
            message: '请输入确认密码',
            trigger: 'blur'
          }, {
            validator: validateRepwd,
            trigger: 'blur'
          }],
          mobile: [{
            required: true,
            message: '请输入手机号码',
            trigger: 'change'
          }, {
            pattern: /^1[3456789]\d{9}$/,
            message: "手机号码格式不正确",
            trigger: "blur"
          }],
          type: [{
            required: true,
            message: '请选择账号类型',
            trigger: 'blur'
          }]

        },
        rowId: 0,

      }
    },
    methods: {
      // 列表数据
      getList() {
        let _this = this
        let params = {
          page: this.page.current,
        }

        getList(params).then(res => {
          if (res.data.status == 1) {
            let result = res.data.data
            _this.data.list = result.list
            _this.page.total = result.total
            _this.page.pageSize = result.size
            _this.data.account_type = result.account_type
            _this.data.account_pid = result.account_pid
            _this.data.roleList = result.roleList
            _this.data.storeList = result.storeList
          }
        }).catch(function(error) {
          // 异常

        })
      },
      changepage(e) {
        this.page.current = e;
        this.getList();

      },
      // 刷新
      refresh() {

        this.getList()
      },
      // 新增
      create() {

        if (!this.role_add) {
          let config = {
            content: '您没有操作权限',
            background: true
          }
          this.$Message.error(config)
          return
        }
        this.createModal = true

        this.createTitle = '添加账号'
        this.isAdd = true
        this.formValidate = {} // 表单重置
        this.formValidate.status = '1';

        this.handleReset('formValidate') // 验证重置
      },
      // 修改
      edit(row) {
        if (!this.role_edit) {
          let config = {
            content: '您没有操作权限',
            background: true
          }
          this.$Message.error(config)
          return
        }
        this.createModal = true
        this.createTitle = '编辑账号'
        this.isAdd = false
        this.formValidate = {} // 表单重置
        this.formValidate = JSON.parse(JSON.stringify(row))
        this.formValidate.status = this.formValidate.status.toString()
        this.formValidate.type = this.formValidate.type.toString()
         // this.formValidate.store_id = this.formValidate.store_id.toString()
         //  this.formValidate.group_id = this.formValidate.group_id.toString()
        this.formValidate.store_id = parseInt(this.formValidate.store_id)
        this.formValidate.group_id = parseInt(this.formValidate.group_id)

        this.handleReset('formValidate') // 验证重置
      },
      handleReset(name) {
        this.$refs[name].resetFields()
      },
      save(name) {

        let _this = this

        this.$refs[name].validate((valid) => {
          if (valid) {
            if (_this.isAdd) {
              // 新增
              let obj = {
                username: _this.formValidate.username,
                nickname: _this.formValidate.nickname,
                password: _this.formValidate.password,
                mobile: _this.formValidate.mobile,
                status: _this.formValidate.status,
                group_id: _this.formValidate.group_id,
                store_id:_this.formValidate.store_id,
                type:_this.formValidate.type,

              }

              // 新增接口
              add(obj).then(res => {
                if (res.data.status == 1) {

                  _this.createModal = false
                  _this.getList() // 重新刷新数据
                  _this.$Message.success('操作成功')
                } else {
                  _this.createModal = false
                  // axios响应拦截
                }
              }).catch(function(error) {
                // 异常
                _this.createModal = false
                console.log(error)
              })
            } else {
              // 修改

              let obj = {
                id: _this.formValidate.id,
               username: _this.formValidate.username,
               nickname: _this.formValidate.nickname,
               password: _this.formValidate.password,
               mobile: _this.formValidate.mobile,
               status: _this.formValidate.status,
               group_id: _this.formValidate.group_id,
               store_id:_this.formValidate.store_id,
               type:_this.formValidate.type,
              }

              // 修改接口
              put(obj).then(res => {
                if (res.data.status == 1) {

                  _this.createModal = false

                  _this.getList() // 重新刷新数据
                  _this.$Message.success('操作成功')
                } else {

                }
              }).catch(function(error) {
                // 异常
                console.log(error)
              })
            }

          } else {
            this.$Message.error('请输入必填项!')
          }
        })
      },

      // 删除
      del(row) {
        if (!this.role_del) {
          let config = {
            content: '您没有操作权限',
            background: true
          }
          this.$Message.error(config)
          return
        }
        this.delId = row.id
        this.delModal = true
        // 删除接口
      },
      confirmDel() {
        let _this = this
        let obj = {
          id: this.delId
        }
        del(obj).then(res => {
          if (res.data.status == 1) {

            _this.delModal = false
            _this.$Message.success('操作成功')
            _this.getList() // 重新刷新数据
          } else {
            _this.delModal = false

          }
        }).catch(function(error) {
          // 异常
          _this.delModal = false
          console.log(error)
        })
      },
      changType(e) {

      }
    }

  }
</script>

<style lang="scss">
  @import "./index";
</style>
